const app = require("express")()
const server = require("http").createServer(app)
const io = require("socket.io")(server)
const dayjs = require("dayjs")
const { setgroups } = require("process")
const router = require("./router")
const fs = require("fs")
const path = require("path")
const { def } = require("@vue/shared")

// app.use('/', express.static(__dirname + '../'))
app.use("/", router)
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Content-Type")
  next()
})

const PORT = 10000
server.listen(PORT, () => {
  console.log(`http://192.168.44.201:${PORT}`)
  // console.log(`http://192.168.122.223:${PORT}`)
})

let currentUserList = []
let coupleUserList = {}

// 只向自己发送消息
// socket.emit()

// 向除了自己的所有人发送消息
// socket.broadcast.emit()

// 向所有人发送更新消息列表
// io.sockets.emit()

// 向指定人发送消息
// io.to(socket.id).emit()

// 连接
io.on("connection", socket => {
  // 获取当前客户端IP
  let ip = socket.handshake.address.match(/(?<=ff:).*/)[0]

  addUser({ id: socket.id, ip })

  // 检查当前客户端ip是否在对战列表中
  if (coupleUserList[ip]) {
    let targetIp = coupleUserList[ip]
    socket.emit("battle", ip > targetIp)
  }

  io.sockets.emit("system:notice", `【系统】${ip} 已上线`)
  io.sockets.emit("system:users", currentUserList)

  // 发送消息，返回当前客户端IP
  socket.emit("address", ip)

  socket.on("getLatestUsers", () => {
    socket.emit("system:users", currentUserList)
  })

  // 监听：发起挑战
  socket.on("send:challenge", targetIp => {
    let target = currentUserList.find(c => c.ip === targetIp)
    // 通过id向指定用户发请求
    if (target) {
      io.to(target.id).emit("receive:challenge", {
        sourceIp: ip,
        message: `${ip} 向你发起挑战！`,
      })
    }

    // socket.broadcast.emit("receive:challenge", {
    //   targetIp,
    //   message: `${ip} 向你发起挑战！`,
    // })
  })

  // 监听：开启游戏
  socket.on("play", data => {
    const { sourceIp, targetIp } = data
    coupleUserList[sourceIp] = targetIp
    coupleUserList[targetIp] = sourceIp
    let source = currentUserList.find(c => c.ip === sourceIp)
    let target = currentUserList.find(c => c.ip === targetIp)
    if (source && target) {
      io.to(source.id).emit("prepare:playing", {
        data,
        msg: `${targetIp} 已接受挑战，正准备进入游戏，请勿关闭页面！`,
      })
      io.to(target.id).emit("prepare:playing", {
        data,
        msg: `已接受 ${sourceIp} 的挑战，正准备进入游戏，请勿关闭页面！`,
      })
    }
  })

  // 监听：更新棋盘
  socket.on("update:board", data => {
    let targetIp = coupleUserList[ip]
    let target = currentUserList.find(c => c.ip === targetIp)
    if (target) {
      // io.to(target.id).emit("update:other-board", data)
      socket.broadcast.emit("update:board", { ip, targetIp, ...data })
    }
  })

  // 监听离线
  socket.on("disconnect", () => {
    removeUser({ ip })
    let targetIp
    ;(targetIp = coupleUserList[ip]) && delete coupleUserList[ip]
    coupleUserList[targetIp] && delete coupleUserList[targetIp]
    socket.broadcast.emit("system:notice", `${ip} 已下线`)
    socket.broadcast.emit("rival:outline", targetIp)
    // console.log(`${ip} 已下线`)
    socket.broadcast.emit("system:users", currentUserList)
  })
})

function addUser(user) {
  if (currentUserList.find(t => t.ip === user.ip)) return
  currentUserList.push(user)
}

function removeUser(user) {
  let target = currentUserList.findIndex(t => t.ip === user.ip)
  currentUserList.splice(target, 1)
}

function updateServerState() {
  const filePath = path.join(__dirname, "/data/User.txt")
  const data = fs.readFileSync(filePath, { encoding: "utf-8" })
  fs.writeFileSync(filePath, data + Date.now())
}

// setInterval(() => {
//   updateServerState()
// }, 5000)
